/*
 * ServicioForm.java
 *
 * Created on May 27, 2011, 3:02 PM
 */

package basededatos;
import javax.swing.*;
//import Forms.*;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.Dimension;
import java.beans.Statement;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableModel;
/**
 *
 * @author  poweruser
 */
public class GestionClientes extends javax.swing.JFrame {

    /** Creates new form ServicioForm */
    public GestionClientes() {
        
        ConectBD();
        initComponents();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        MasterTable = new javax.swing.JTable();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        idcliente = new javax.swing.JTextField();
        nombre = new javax.swing.JTextField();
        apellido = new javax.swing.JTextField();
        direccion = new javax.swing.JTextField();
        boton_nuevo = new javax.swing.JButton();
        boton_eliminar = new javax.swing.JButton();
        boton_guardar = new javax.swing.JButton();
        boton_actualizar = new javax.swing.JButton();
        telefono = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();

        setTitle("Gestion de Clientes");
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });

        JList list;
        ListSelectionModel listSelectionModel;
        DefaultTableModel modelo = new DefaultTableModel();
        listSelectionModel = MasterTable.getSelectionModel();
        listSelectionModel.addListSelectionListener(new SharedListSelectionHandler());
        MasterTable.setSelectionModel(listSelectionModel);
        MasterTable.setModel(modelo
        );
        try{
            java.sql.Statement inst = conexion.createStatement();
            String querry = "Select * from cliente";
            ResultSet rs = inst.executeQuery(querry);
            //Obteniendo datos de la base de datos e ingresandolos a una Jtable
            //DefaultTableModel modelo = new DefaultTableModel();
            //JTable tabla = new JTable(modelo);
            ResultSetMetaData metaDatos = rs.getMetaData();
            int numColumnas = metaDatos.getColumnCount();
            Object[] etiquetas = new Object[numColumnas];
            for (int i = 0; i < numColumnas; i++) {
                etiquetas[i] = metaDatos.getColumnLabel(i + 1);
                //System.out.println(etiquetas[i]);
            }
            modelo.setColumnIdentifiers(etiquetas);
            while (rs.next()) {
                Object[] fila = new Object[numColumnas];
                for (int j = 0; j < numColumnas; j++) {
                    fila[j] = rs.getObject(j + 1);
                }
                modelo.addRow(fila);
            }

            inst.execute("END");
            inst.close();
        }catch(Exception e){

        }
        MasterTable.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                MasterTableMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(MasterTable);

        jLabel1.setText("ID Cliente:");

        jLabel2.setText("Nombre");

        jLabel3.setText("Apellido");

        jLabel4.setText("Direccion");

        idcliente.setEditable(false);

        nombre.setEditable(false);
        nombre.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                nombreActionPerformed(evt);
            }
        });

        apellido.setEditable(false);

        direccion.setEditable(false);

        boton_nuevo.setText("Nuevo");
        boton_nuevo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                boton_nuevoActionPerformed(evt);
            }
        });

        boton_eliminar.setText("Eliminar");
        boton_eliminar.setEnabled(false);
        boton_eliminar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                boton_eliminarActionPerformed(evt);
            }
        });

        boton_guardar.setText("Guardar");
        boton_guardar.setEnabled(false);
        boton_guardar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                boton_guardarActionPerformed(evt);
            }
        });

        boton_actualizar.setText("Actualizar");
        boton_actualizar.setEnabled(false);
        boton_actualizar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                boton_actualizarActionPerformed(evt);
            }
        });

        telefono.setEditable(false);

        jLabel5.setText("Telefono:");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 376, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(idcliente, javax.swing.GroupLayout.DEFAULT_SIZE, 321, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel2)
                            .addComponent(jLabel3)
                            .addComponent(jLabel4))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(apellido, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 323, Short.MAX_VALUE)
                            .addComponent(telefono, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 323, Short.MAX_VALUE)
                            .addComponent(direccion, javax.swing.GroupLayout.DEFAULT_SIZE, 323, Short.MAX_VALUE)
                            .addComponent(nombre, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 323, Short.MAX_VALUE)))
                    .addComponent(jLabel5)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(boton_nuevo)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(boton_eliminar)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(boton_guardar)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(boton_actualizar)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(10, 10, 10)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 158, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel1)
                    .addComponent(idcliente, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(21, 21, 21)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel2)
                    .addComponent(nombre, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(apellido, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(direccion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(telefono, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(boton_nuevo)
                    .addComponent(boton_eliminar)
                    .addComponent(boton_guardar)
                    .addComponent(boton_actualizar))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents


private void nombreActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_nombreActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_nombreActionPerformed

private void boton_nuevoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_boton_nuevoActionPerformed
    boton_guardar.setEnabled(true);
    //idservicio.setEditable(true);
    nombre.setEditable(true);
    apellido.setEditable(true);
    direccion.setEditable(true);
    telefono.setEditable(true);

    
    idcliente.setText(null);
    nombre.setText("");
    apellido.setText("");
    direccion.setText("");
    telefono.setText("");
    
    
}//GEN-LAST:event_boton_nuevoActionPerformed

private void MasterTableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_MasterTableMouseClicked
    //boton_eliminar.setEnabled(false);
    //boton_guardar.setEnabled(false);
}//GEN-LAST:event_MasterTableMouseClicked

private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
    CloseConection();
}//GEN-LAST:event_formWindowClosing

private void boton_guardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_boton_guardarActionPerformed
    
    String ID = idcliente.getText();
    String Nombre = nombre.getText();
    String ap = apellido.getText();
    String Dir= direccion.getText();
    String Tel=telefono.getText();
    
    //System.out.println(tipo);
    try {
            java.sql.Statement inst = conexion.createStatement();
            //INSERT INTO cliente VALUES ($1, $2);
            String querry = "Select NuevoCliente('"+Nombre+"','"+ap+"','"+Dir+"',"+Tel+")";
            //System.out.println(querry);
            ResultSet rs = inst.executeQuery(querry);
            this.updateMasterTable();

        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(null, ex.getMessage());
            //Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }
}//GEN-LAST:event_boton_guardarActionPerformed

private void boton_actualizarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_boton_actualizarActionPerformed
    String ID = idcliente.getText();
    String Nombre = nombre.getText();
    String ap = apellido.getText();
    String Dir= direccion.getText();
    String Tel=telefono.getText();
    try {
            java.sql.Statement inst = conexion.createStatement();
            inst.executeUpdate("UPDATE Cliente SET  nombre='"+Nombre
                    +"', apellido='"+ap+"' ,direccion='"+Dir+"' ,telefono="+Tel+" WHERE idcliente="+ID);
            //INSERT INTO cliente VALUES ($1, $2);
            //String querry = "UPDATE Servicio SET idcarga="+carga+", montoservicio="+Monto
                  //  +", tipo='"+Tipo+"' WHERE idservicio="+servicio;
            //System.out.println(querry);
            //ResultSet rs = inst.executeQuery(querry);
            this.updateMasterTable();

        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(null, ex.getMessage());
            //Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }

}//GEN-LAST:event_boton_actualizarActionPerformed

private void boton_eliminarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_boton_eliminarActionPerformed
    String ID = idcliente.getText();
    System.out.println(ID);

    try {
            java.sql.Statement inst = conexion.createStatement();
            inst.executeUpdate("DELETE FROM Cliente WHERE idcliente="+ID);
           
            this.updateMasterTable();

        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(null, ex.getMessage());
            //Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }
}//GEN-LAST:event_boton_eliminarActionPerformed

private static Connection conexion;
    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                  new GestionClientes().setVisible(true);
            }
        });
    }
    
    public void CloseConection(){
        try {
            conexion.close();
        } catch (SQLException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    public void ConectBD(){
        String driver, user, pass, direccion;
                try {
                    driver = "org.postgresql.Driver";
                    user = ParseXML.user;
                    pass = ParseXML.passwd;
                    direccion = "jdbc:postgresql://localhost:5432/serbd/";

                    Class.forName(driver);
                    conexion = DriverManager.getConnection(direccion, user, pass);
                    //System.out.println("Se ha conectado exitosamente a la BD");
                    //new Main().setVisible(true);
                    
                    //SetClientComboBox();
                    //conexion.close();
                } catch (Exception e) {
                    System.out.println("No se pudo realizar la Conexion");
                    e.printStackTrace();
                }
    }
    
    public void getDatos(){
         try {
             
            java.sql.Statement inst = conexion.createStatement();
            String querry = "Select * from cliente";
            ResultSet rs = inst.executeQuery(querry);
            //Obteniendo datos de la base de datos e ingresandolos a una Jtable
            DefaultTableModel modelo = new DefaultTableModel();
            JTable tabla = new JTable(modelo);
            ResultSetMetaData metaDatos = rs.getMetaData();
            int numColumnas = metaDatos.getColumnCount();
            Object[] etiquetas = new Object[numColumnas];
            for (int i = 0; i < numColumnas; i++) {
                etiquetas[i] = metaDatos.getColumnLabel(i + 1);
                System.out.println(etiquetas[i]);
            }
            modelo.setColumnIdentifiers(etiquetas);
            while (rs.next()) {
                Object[] fila = new Object[numColumnas];
                for (int j = 0; j < numColumnas; j++) {
                    fila[j] = rs.getObject(j + 1);
                }
                modelo.addRow(fila);
            }

            inst.execute("END");
            inst.close();
            // Agregar la tabla a un Panel
            JScrollPane scroll = new JScrollPane(tabla);
            //tabla.setAutoResizeMode(tabla.AUTO_RESIZE_ALL_COLUMNS);
            tabla.setVisible(true);
            JPanel panel = new JPanel();
            panel.add(scroll);
            JFrame frame = new JFrame();
            frame.add(panel);
            frame.pack();
            frame.setVisible(true);
            
        } catch (SQLException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    public void updateMasterTable(){
        //System.out.println("Actualizando....");
        DefaultTableModel modelo = new DefaultTableModel();
        MasterTable.setModel(modelo);
        try {
            java.sql.Statement inst = conexion.createStatement();
            String querry = "Select * from cliente";
            ResultSet rs = inst.executeQuery(querry);
            //Obteniendo datos de la base de datos e ingresandolos a una Jtable
            //DefaultTableModel modelo = new DefaultTableModel();
            //JTable tabla = new JTable(modelo);
            ResultSetMetaData metaDatos = rs.getMetaData();
            int numColumnas = metaDatos.getColumnCount();
            Object[] etiquetas = new Object[numColumnas];
            for (int i = 0; i < numColumnas; i++) {
                etiquetas[i] = metaDatos.getColumnLabel(i + 1);
                //System.out.println(etiquetas[i]);
            }
            modelo.setColumnIdentifiers(etiquetas);
            while (rs.next()) {
                Object[] fila = new Object[numColumnas];
                for (int j = 0; j < numColumnas; j++) {
                    fila[j] = rs.getObject(j + 1);
                }
                modelo.addRow(fila);
            }

            inst.execute("END");
            inst.close();
        } catch (Exception e) {
        }
    }
    
    class SharedListSelectionHandler implements ListSelectionListener {
        public void valueChanged(ListSelectionEvent e) { 
            ListSelectionModel lsm = (ListSelectionModel)e.getSource();
            try{
                int firstIndex = e.getFirstIndex();
                int lastIndex = e.getLastIndex();

                int fila=0;

                if (lsm.isSelectionEmpty()) {
                    //output.append(" <none>");
                } else {
                    // Find out which indexes are selected.
                    int minIndex = lsm.getMinSelectionIndex();
                    int maxIndex = lsm.getMaxSelectionIndex();
                    for (int i = minIndex; i <= maxIndex; i++) {
                        if (lsm.isSelectedIndex(i)) {
                            fila=i;
                           // System.out.println("FILA: " + i);
                        }
                    }
                }
                
                idcliente.setText(MasterTable.getValueAt(fila, 0)+"");
                nombre.setText(MasterTable.getValueAt(fila, 1)+"");
                apellido.setText(MasterTable.getValueAt(fila, 2)+"");
                direccion.setText(MasterTable.getValueAt(fila, 3)+"");
                telefono.setText(MasterTable.getValueAt(fila, 4)+"");

                nombre.setEditable(true);
                apellido.setEditable(true);
                direccion.setEditable(true);
                telefono.setEditable(true);
                boton_guardar.setEnabled(false);
                boton_eliminar.setEnabled(true);
                boton_actualizar.setEnabled(true);
            }catch(Exception exe){
                //System.out.println("exception loca");
            }
            
        }
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTable MasterTable;
    private javax.swing.JTextField apellido;
    private javax.swing.JButton boton_actualizar;
    private javax.swing.JButton boton_eliminar;
    private javax.swing.JButton boton_guardar;
    private javax.swing.JButton boton_nuevo;
    private javax.swing.JTextField direccion;
    private javax.swing.JTextField idcliente;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextField nombre;
    private javax.swing.JTextField telefono;
    // End of variables declaration//GEN-END:variables

}


